package com.riant.myspring.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname MyApplicationContext
 * @Description TODO
 * @Date 2021/5/7 23:47
 * @Created by 张斌
 */
public class MyApplicationContext {

    private Class configClass;
    //单例池
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    //bean定义map
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public MyApplicationContext(Class configClass) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        this.configClass = configClass;
        //解析配置类
        //ComponentScan--》扫描路径--》扫描
        scan(configClass);
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    public void scan(Class configClass) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        ComponentScan componentScan = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();//扫描路径
        System.out.println("扫描路径：" + path);
        //扫描路径下的文件
        path = path.replace(".", "/");
        ClassLoader classLoader = MyApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File item : files) {
                String fileName = item.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("\\", ".");
                    System.out.println(className);
                    Class<?> aclass = classLoader.loadClass(className);
                    if (aclass.isAnnotationPresent(Component.class)) {
                        //表示当前类是一个bean
                        //解析类，判断当前bean是单例bean，还是protoTypeBean
                        //beanDefinition
                        //当前类是否实现了BeanPostProcessor接口
                        if (BeanPostProcessor.class.isAssignableFrom(aclass)) {
                            BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aclass.getDeclaredConstructor().newInstance();
                            beanPostProcessorList.add(beanPostProcessor);
                        }
                        Component componentAnnotation = aclass.getDeclaredAnnotation(Component.class);
                        String beanName = componentAnnotation.value();
                        BeanDefinition beanDefinition = new BeanDefinition();
                        beanDefinition.setClazz(aclass);
                        if (aclass.isAnnotationPresent(Scope.class)) {
                            Scope scopeAnnotation = aclass.getDeclaredAnnotation(Scope.class);
                            beanDefinition.setScope(scopeAnnotation.value());
                        } else {
                            beanDefinition.setScope("singleton");
                        }
                        beanDefinitionMap.put(beanName, beanDefinition);
                    }
                }

            }
        }
    }

    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object o = singletonObjects.get(beanName);
                return o;
            } else {
                //创建bean对象
                return createBean(beanName, beanDefinition);
            }
        } else {
            throw new NullPointerException();
        }
    }

    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            //依赖注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    Autowired autowired = field.getDeclaredAnnotation(Autowired.class);
                    Object fieldObject = getBean(field.getName());
                    //autowired注解属性required为true时
                    if (null == fieldObject && autowired.required() == true) {
                        throw new NullPointerException();
                    }
                    field.setAccessible(true);
                    field.set(instance, fieldObject);
                }
            }
            //当bean实现了beanNameAware接口，则需要设置beanName
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }
            //bean初始化前操作
            for (BeanPostProcessor beanPostProcessor:beanPostProcessorList){
                beanPostProcessor.postProcessBeforeInitialization(instance,beanName);
            }

            //初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor:beanPostProcessorList){
                 return beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }

            return instance;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
